package com.avic.rong.userOrder.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avic.rong.R;
import com.avic.rong.userOrder.activity.AddressListActivity;
import com.avic.rong.userOrder.activity.UpdateAddressActivity;
import com.avic.rong.userOrder.api.DeleteAddressApi;
import com.avic.rong.userOrder.api.SetDefaultAddressApi;
import com.avic.rong.userOrder.bean.AddressListBean;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by XinEr on 2019/7/16.
 * Describe:
 */
public class EditAddressAdapter extends RecyclerView.Adapter<EditAddressAdapter.ViewHolder> implements View.OnClickListener {
    private Context context;
    private ArrayList<AddressListBean> listData;


    public int mSelectedPos = -1;//保存当前选中的position
    private boolean DEFAULT_ADDRESS = false;
    //默认地址选择
    private int selectedPositon = -2;
    //地址选择
    public int address_postion=-3;
    private int ADDRESS_SELECT_RESULT = 101;
    private int addressId;
    //不做任何操作，点击返回键需要的
    private int backSelect=-5;

    private String intentType;
    private String enterType;

    public EditAddressAdapter(Context context, ArrayList<AddressListBean> listData,int addressId,String intentType) {
        this.context = context;
        this.listData = listData;
        this.addressId=addressId;
        this.intentType=intentType;
    }

    public String getEnterType() {
        return enterType;
    }

    public void setEnterType(String enterType) {
        this.enterType = enterType;
    }

    public int getBackSelect() {
        return backSelect;
    }

    public void setBackSelect(int backSelect) {
        this.backSelect = backSelect;
    }

    public void setAddress_postion(int address_postion) {
        this.address_postion = address_postion;
    }

    public int getAddress_postion() {
        return address_postion;
    }

    public void setSelectedPositon(int selectedPositon) {
        this.selectedPositon = selectedPositon;
    }

    public int getmSelectedPos() {
        return mSelectedPos;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View inflate = LayoutInflater.from(context).inflate(R.layout.edit_address_item, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(inflate);
        viewHolder.itemView.setOnClickListener(this);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder viewHolder, final int i) {

    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, final int position, @NonNull List<Object> payloads) {
        super.onBindViewHolder(holder, position, payloads);
        final View finalView = holder.itemView;
        holder.itemView.setTag(position);
        final AddressListBean addressListBean = listData.get(position);
//        if (payloads.isEmpty()) {//payloads即有效负载，当首次加载或调用notifyDatasetChanged() ,notifyItemChange(int position)进行刷新时，payloads为empty 即空
////            holder.tv_tag_way.setText(payloads.get(position).getName());
//            holder.iv_address_select.setRJCPSelected(mSelectedPos == position);
//        } else {//当调用notifyItemChange(int position, Object payload)进行布局刷新时，payloads不会empty ，所以真正的布局刷新应该在这里实现
//            holder.iv_address_select.setRJCPSelected(mSelectedPos == position);
//        }
//        if (address_postion == -3&&address_postion != position){

        if (enterType!=null&&enterType.equals("设置")){
            holder.iv_address_select.setVisibility(View.GONE);
        }
        if (addressId!=-1&&addressId==addressListBean.getAddressId()){
            holder.iv_address_select.setSelected(true);
            backSelect=1;
        }
//        }

        if (addressListBean!=null){
            if (addressListBean.getIsDefault() == 1) {
                holder.tv_default_tag.setVisibility(View.VISIBLE);
//            holder.iv_address_select.setWdDrawerSelected(true);
                ((SwipeMenuLayout) (finalView)).setSwipeEnable(false);
            } else {
                holder.tv_default_tag.setVisibility(View.GONE);
            }
        }

        if (address_postion == position && address_postion != -3) {
            holder.iv_address_select.setSelected(true);
        } else if (address_postion != -3) {
            holder.iv_address_select.setSelected(false);
        }


        if (selectedPositon == position && selectedPositon != -2) {
            holder.tv_default_tag.setVisibility(View.VISIBLE);
            ((SwipeMenuLayout) (finalView)).setSwipeEnable(false);
        } else if (selectedPositon != -2) {
            holder.tv_default_tag.setVisibility(View.GONE);
        }

        //勾选地址
        holder.ll_select_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (mSelectedPos != position) {//当前选中的position和上次选中不是同一个position 执行
//                    holder.iv_address_select.setRJCPSelected(true);
//                    if (mSelectedPos != -1) {//判断是否有效 -1是初始值 即无效 第二个参数是Object 随便传个int 这里只是起个标志位
//                        notifyItemChanged(mSelectedPos, 0);
//                    }
//                    mSelectedPos = position;
//                }
                //被选中的收货地址排在第一位，其余地址按照修改时间倒序排列
//                setAddress_postion(position);
//                checkAddress(listData, addressListBean.getAddressId());
                if (enterType!=null&&enterType.equals("设置"))return;
                Intent intent = new Intent();
                intent.putExtra("address_bean",listData.get(position));
                ((AddressListActivity) context).setResult(((AddressListActivity) context).RESULT_OK, intent);
                notifyDataSetChanged();



                ((AddressListActivity) context).finish();
            }
        });

        holder.tv_user_name.setText(addressListBean.getConsignee());
        holder.tv_phone.setText(addressListBean.getTel());
        holder.tv_address_name.setText(addressListBean.getProvinceName() + addressListBean.getCityName() + addressListBean.getAddress());

        //删除地址
        holder.tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final DeleteAddressApi deleteAddressApi = new DeleteAddressApi((AddressListActivity) context, simpleOnNextListener);
                deleteAddressApi.setAddressId(addressListBean.getAddressId() + "");
                deleteAddressApi.setCache(false);
                HttpManager.getInstance().doHttpDeal(deleteAddressApi);
                ((SwipeMenuLayout) (finalView)).quickClose();
                if (addressListBean.getIsDefault() != 1) {
                    listData.remove(position);
                    notifyDataSetChanged();
                }
                if (addressListBean.getIsDefault() == 1) {

//            holder.iv_address_select.setWdDrawerSelected(true);
                    holder.sm_side.quickClose();
                }

            }
        });
        //设置默认地址
        holder.tv_default.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> map = new HashMap<>();
                map.put("token", SharedPreferencesUtil.getLoginToken());
                map.put("addressId", addressListBean.getAddressId() + "");
                SetDefaultAddressApi setDefaultAddressApi = new SetDefaultAddressApi((AddressListActivity) context, simpleOnNextListener);
                setDefaultAddressApi.setCache(false);
                setDefaultAddressApi.setMap(map);
                HttpManager.getInstance().doHttpDeal(setDefaultAddressApi);

                ((SwipeMenuLayout) (finalView)).quickClose();
//                setSelectedPositon(position);
//                notifyDataSetChanged();


                if (addressListBean.getIsDefault() == 1) {

//            holder.iv_address_select.setWdDrawerSelected(true);

//                    ((SwipeMenuLayout) holder.itemView).setIos(false).setLeftSwipe(position % 2 == 0 ? true : false).setSwipeEnable(false);
                }
            }
        });
        //修改地址
        holder.iv_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //1  添加地址   2   修改地址
                Intent intent = new Intent(context, UpdateAddressActivity.class);
                intent.putExtra("address", 2);
                intent.putExtra("address_bean",listData.get(position));
                //地址跳转标记
                if (!TextUtils.isEmpty(intentType)){
                    intent.putExtra("intentType",intentType);
                }

                context.startActivity(intent);
            }
        });

        holder.setIsRecyclable(false);

    }

    @Override
    public int getItemCount() {
        return listData.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private ImageView iv_address_select;
        private TextView tv_user_name;
        private TextView tv_phone;
        private TextView tv_default_tag;
        private TextView tv_address_name;
        private ImageView iv_update;
        private TextView tv_default;
        private TextView tv_delete;
        private SwipeMenuLayout sm_side;
        private LinearLayout ll_select_address;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            iv_address_select = itemView.findViewById(R.id.iv_address_select);
            tv_user_name = itemView.findViewById(R.id.tv_user_name);
            tv_phone = itemView.findViewById(R.id.tv_phone);
            tv_default_tag = itemView.findViewById(R.id.tv_default_tag);
            tv_address_name = itemView.findViewById(R.id.tv_address_name);
            iv_update = itemView.findViewById(R.id.iv_update);
            tv_default = itemView.findViewById(R.id.tv_default);
            tv_delete = itemView.findViewById(R.id.tv_delete);
            sm_side = itemView.findViewById(R.id.sm_side);
            ll_select_address = itemView.findViewById(R.id.ll_select_address);

        }
    }

    public interface OnClickItem {
        void OnClickListion(View view, int postion);
    }

    private EditAddressAdapter.OnClickItem onClickItem;

    @Override
    public void onClick(View v) {
        if (onClickItem != null) {
            onClickItem.OnClickListion(v, (int) v.getTag());
        }
    }

    public void setOnClickItem(EditAddressAdapter.OnClickItem onClickItem) {
        this.onClickItem = onClickItem;
    }

    //权威评测
    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }
            ((AddressListActivity) context).initData();

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {

        }
    };



}
